from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime
from stock_control.positionDB import PositionDB

from stock_control.emailSender import EmailSender
from stock_control.my_tushare import get_previous_trading_day, is_open


class ControlPurchaseStock:
    def __init__(self, strategy):
        self.strategy = strategy

    # 制定购买计划
    def make_plan(self):
        #ces
        print("\n制定计划中：")
        # 判断当日是否开市
        today = datetime.now().strftime("%Y%m%d")
        # 开市：找到前一次开市的日期，用上次开市的数据制定今天的购买计划
        if is_open(today):
            preday = get_previous_trading_day(today)
            # 遍历每个策略类，调用每个策略类的制定购买计划函数
            #ces
            print("今日开市：使用上一次开市(" + preday + ")的股票信息作为购买计划的依据")
            for s in self.strategy:
                s.make_purchase_plan(preday)
            print('(', datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "计划制定完成)\n")
        else:
            # 闭市：不用制定计划
            print("今日闭市\n")

    # 购买股票
    def purchase_stock(self):
        # 判断当日是否开市
        today = datetime.now().strftime("%Y%m%d")
        # 测试
        print('\n购买股票中：')
        # 开市：按照购买计划购买股票
        if is_open(today):
            # 得到的today格式为YYYYMMDD，将其改为YYYY-MM-DD传给各策略类的购买股票函数
            # today = today[0:4] + '-' + today[4:6] + '-' + today[6:8]
            # 遍历每个策略类，调用每个策略类的购买股票函数
            for s in self.strategy:
                s.buy_stock(today)
            # 发送邮件给用户
            es = EmailSender()
            # es.send_system_condition(datetime.now().strftime("%Y-%m-%d"), 'buy')
            print('(', datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "购买股票完成)\n")
        else:
            # 闭市：不用购买股票
            print("今日闭市\n")

    # 卖出股票sale_stock
    def sale_stock(self):
        print('\n正在卖出股票：')
        # 判断当日是否开市
        today = datetime.now().strftime("%Y%m%d")
        # 开市：按照购买计划购买股票
        if is_open(today):
            # 遍历每个策略类，调用每个策略类的卖出股票函数
            for s in self.strategy:
                s.sale_stock(today)
                # 发送邮件给用户
                es = EmailSender()
                # es.send_system_condition(datetime.now().strftime("%Y-%m-%d"), 'sell')
            print('(', datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "股票出售完成)\n")
            # 更新持仓临时表中的股票收盘价
            PositionDB().update_position(today)
        # 闭市：不用购买股票
        else:
            # 闭市：不用购买股票
            print("今日闭市\n")

    # 控制股票交易的函数
    def control_transaction(self):
        scheduler = BackgroundScheduler()
        scheduler.add_job(self.make_plan, 'cron', day='*', hour=9, minute=0)
        scheduler.add_job(self.purchase_stock, 'cron', day='*', hour=9, minute=35)
        scheduler.add_job(self.sale_stock, 'cron', day='*', hour=14, minute=50)
        scheduler.start()
        while True:
            print('股票交易系统模拟演示')
            print('1.模拟制定购买计划')
            print('2.模拟买入股票')
            print('3.模拟卖出股票')
            choice = input('输入对应序号进行模拟：')
            while choice != '1' and choice != '2' and choice != '3':
                choice = input('输入不符合要求，请重新输入：')
            if choice == '1':
                self.make_plan()
            elif choice == '2':
                self.purchase_stock()
            elif choice == '3':
                self.sale_stock()


'''
显示部分全部从数据库走，显示到前端
class ControlDisplayInfo:
    def __init__(self, strategy):
        self.strategy = strategy

    # 查看当日股票买卖情况（通过数据库）
    @staticmethod
    def display_transaction_info(self):
        print('\n当日股票买卖情况')
        # 获得当天日期
        today = datetime.now().strftime("%Y-%m-%d")
        sql = "select * from t_log where op_time like " + '"' + today + '%"'
        result = LogDB().search(sql)
        print(DataFrame(result))

    # 查看当前持仓情况及收益（通过各个策略的持仓队列）
    def display_position_info(self):
        print('\n当前持仓情况及收益率')
        for s in self.strategy:
            print(s.name + "：")
            print(s.position)

    # 查看历史买卖数据（日志）（通过数据库）
    @staticmethod
    def display_history_info(self):
        print('\n历史买卖数据（日志）')
        sql = "select * from t_log order by op_time desc"
        result = LogDB().search(sql)
        print(DataFrame(result))

    # 控制查看交易信息的函数
    def control_display(self):
        while True:
            print('股票交易系统')
            print('1.查看今日股票买卖情况')
            print('2.查看当前持仓情况及收益')
            print('3.查看历史股票交易情况（日志）')
            choice = input('输入对应序号查看信息：')
            while choice != '1' and choice != '2' and choice != '3':
                choice = input('输入不符合要求，请重新输入：')
            if choice == '1':
                self.display_transaction_info(self)
            elif choice == '2':
                self.display_position_info()
            elif choice == '3':
                self.display_history_info(self)
'''
if __name__ == '__main__':
    control_purchase = ControlPurchaseStock()
    control_purchase.control_transaction()
    # control_display = ControlDisplayInfo()
    # control_display.control_display()
